#include "consumer_mqtt.h"

#include "business_def.h"
#include "Log.h"
//
#include "py_mqtt.h"
#ifdef WIN32
#define usleep(x) Sleep(x)
#endif

ConsumerMQTT::ConsumerMQTT(PyMQTTIO *mqttcpp_)
	: running(true)
	, mqttcpp(mqttcpp_)
{
	mqttcpp->sub_s = "P" + mqttfunc.getAreaID() + "-order";	//重设订购主题,后续支持从配置文件读取
}

ConsumerMQTT::~ConsumerMQTT()
{
	running = false;
}

void* ConsumerMQTT::run()
{
	int ret = 0;
	while (running)
	{
		if (NULL!= mqttcpp&&mqttcpp->link)
		{
			ret = mqttcpp->loop_read();
			if (MOSQ_ERR_SUCCESS != ret)
			{
				mqttcpp->link = false;
				Print_WARN("mqttcpp loop_read error(%d)\n", ret);
			}
		}
		frameProcess();
		usleep(10);
	}
	return NULL;
}

void ConsumerMQTT::frameProcess()
{
	std::string buf_data = "";
	if (mqttcpp->pop_rec(buf_data))
	{
		ControlFromMqtt mrsfc;//来自上层应用的下控数据集
		if (mqttfunc.AddFrame((char*)buf_data.c_str()
			, static_cast<int>(buf_data.length()), mrsfc) > 0) //帧解析
		{
			//帧校验
			if (mqttfunc.CheckFrame(mrsfc))
			{
				mqttcpp->add_rep(buf_data);
			}
		}
	}
};
